package com.ml4ai.backend.services.mappers;

import com.ml4ai.backend.domain.base.BaseAuditEntity;
import com.ml4ai.backend.dto.base.BaseAuditDTO;

/**
 * Created by leecheng on 2017/9/13.
 */
public abstract class BaseMapper<E extends BaseAuditEntity, D extends BaseAuditDTO> implements BaseMapperWrapper<E, D> {

    public abstract E newEntity();

    public abstract D newDTO();

    public abstract E find(Long id);

    public abstract void entity2dto(E entity, D dto);

    public abstract void dto2entity(D dto, E entity);

    public D e2d(E entity) {
        if (entity != null) {
            D dto = newDTO();
            entity2dto(entity, dto);
            return dto;
        } else {
            return null;
        }
    }

    public E d2e(D dto) {
        if (dto != null) {
            E entity = null;
            if (dto.getId() != null) {
                entity = find(dto.getId());
            }
            if (entity == null) {
                entity = newEntity();
            }
            dto2entity(dto, entity);
            return entity;
        } else {
            return null;
        }
    }

}
